package co.yixiang.utils;

import co.yixiang.api.ApiResult;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 验证码短信示例代码
 */
public class VerifyUtil {


    private static final int ConnectionRequestTimeout = 5000;//从连接池中获取连接的超时时间
    private static final int ConnectTimeout = 60000;//与服务器连接超时时间：httpclient会创建一个异步线程用以创建socket连接，此处设置该socket的连接超时时间
    private static final int SocketTimeout = 60000;//socket读数据超时时间：从服务器获取响应数据的超时时间
    private static final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(ConnectionRequestTimeout).setConnectTimeout(ConnectTimeout).setSocketTimeout(SocketTimeout).build();


    public static void main(String[] args) throws IOException {

//        String[] str = new String[]{"key","side","image"};
//        String[] val = new String[]{"3a5e044b74effe6575ff455a587c480a","front","/9j/2wBDAAwJCgsKEQ0XFRcODg0PEyAVExISEyccHhcgLikxMC4pLSwzOko+MzZGNywtQFdBRkxOUlNSMj5aYVpQYEpRUk//2wBDAQ0ODhMREyYVFSZPNS01T09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0//wAARCAKAAeADASIAAhEBAxEB/8QAGwAAAwADAQEAAAAAAAAAAAAAAAECAwQFBgf/xABAEAABAwMCBAQDBgQGAgICAwABAAIRAwQhEjEFQVFhBhMicTKBkRQjQlKhsRVywdEkM0NTYpIW4TRz8PEHorL/xAAaAQEBAQEBAQEAAAAAAAAAAAAAAQIDBAUG/8QAKhEBAA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iDsgIbAVtgBQLKGxlU+fT1ImOymEFNPZDnmdgmC0dUgJJ6BAaTzPdSxuorM6YUsBJwgrDMJS3CHt077ohBWsA4AjuroVq1s8VKZ0Pbz6rDCyNY5yzasWjUrHT0t46lxnh76gAFe1Opw6dQuTwKnbuqOq1IFG1Z5jh+Y8h9Vr2N06yqahLqThFRk/EFqtphxdEhpJgduS8uLBOPdPr6am2+2y+pW4lXc8y6rXf6R77Lp+IKtO2bbWdMyy3GuuR+Kod/osvAWUrNlxdvHptxpog/iqFczh1q/idzDjAeTUrPP4WjJK3Ot7+oRuUj/AA60fUGLq9Bp0RzazmfnsuU2g9sL3NlwNnGnNuHnRbRooU28mDAXareHuG+U8BgBDcOnKzWZ1vQ4Xgm4var6jHOc+2Y38XIqf/5Ac1pswI1DUfkuM/jtawZ5Nt900H7yrHqc7t2XKvb64vXh9VzqjwIBPILWPHHuIJa8OcOSbG1G8"};
//
//        Map<String, Object> map = sendPost("http://apis.juhe.cn/idimage/verify", str, val);

//        Map<String, Object> map = VerifyUtil.sendGet("http://v.juhe.cn/verifybankcard4/query?key=510dd1cbc01ea55285e1da9b4891badb&realname=张三&bankcard=6212261302018916840&idcard=342401199901113838&mobile=13155380813");

        String url = "http://v.juhe.cn/verifybankcard4/query?key=510dd1cbc01ea55285e1da9b4891badb&realname=REALNAME&bankcard=BANKCARD&idcard=IDCARD&mobile=MOBILE";
        url = url.replace("REALNAME" , "张三");
        url = url.replace("BANKCARD" ,"6212261302018916840");
        url = url.replace("IDCARD" , "342401199901113838");
        url = url.replace("MOBILE" , "13155380813");
        Map<String, Object> map = VerifyUtil.sendGet(url);
        String entity = String.valueOf(map.get("entity"));
        JSONObject jsonObject = JSONObject.parseObject(entity);
        if (!jsonObject.getString("error_code").equals("0")){
//            return ApiResult.fail(jsonObject.getString("reason"));
            System.out.println(jsonObject.getString("reason"));
        }
        System.out.println(map);
    }


    //发送post请求,参数为键值对
    public static Map<String, Object> sendPost(String url,
                                               String[] name,
                                               String[] value) throws IOException {

        // 获取默认的请求客户端,CloseableHttpClient是HttpClient的实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        // 设置超时
        httpPost.setConfig(requestConfig);

        //添加传参
        List<NameValuePair> list = new ArrayList<>();
        for (int i = 0; i < name.length; i++) {
            BasicNameValuePair basicNameValuePair = new BasicNameValuePair(name[i].trim(), value[i].trim());//trim():去掉字符串首尾的空格
            list.add(basicNameValuePair);
        }
        httpPost.setEntity(new UrlEncodedFormEntity(list));
        LocalTime startTime = LocalTime.now();//响应开始时间
        CloseableHttpResponse response = httpClient.execute(httpPost);
        LocalTime endTime = LocalTime.now();//响应结束时间
        int code = response.getStatusLine().getStatusCode();
        if (code != 200) {
            System.out.println(url + response);
        }
        Map<String, Object> map_re = new HashMap<>();
        map_re.put("code", code);
        map_re.put("entity", EntityUtils.toString(response.getEntity(), "UTF-8"));
        map_re.put("responseTime", Duration.between(startTime, endTime).toMillis());
        response.close();
        httpClient.close();
        return map_re;
    }


    //发送get请求,参数为键值对
    public static Map<String, Object> sendGet(String url) throws IOException {

        // 获取默认的请求客户端,CloseableHttpClient是HttpClient的实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        // 设置超时
        httpGet.setConfig(requestConfig);
        LocalTime startTime = LocalTime.now();//响应开始时间
        CloseableHttpResponse response = httpClient.execute(httpGet);
        LocalTime endTime = LocalTime.now();//响应结束时间
        int code = response.getStatusLine().getStatusCode();
        if (code != 200) {
            System.out.println(url + response);
        }
        Map<String, Object> map_re = new HashMap<>();
        map_re.put("code", code);
        map_re.put("entity", EntityUtils.toString(response.getEntity(), "UTF-8"));
        map_re.put("responseTime", Duration.between(startTime, endTime).toMillis());
        response.close();
        httpClient.close();
        return map_re;
    }

}

